package com.ibm.test.consumer.rest;

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JobAdminResource {
	int jobIdSeq = 1;
	HashMap<String, Object> jobTable = new HashMap<>();// 实际要保存到DB

	@PostMapping("/async-jobs/{jobType}")
	public Map<String, Object> startJob(@PathVariable("jobType") String jobType) {
		HashMap<String, Object> jobRst = new HashMap<>();
		String id = "TEST-JOB-" + jobIdSeq++;
		jobRst.put("remoteJobId", id);
		TestJobRunner job = new TestJobRunner();
		job.start();
		jobTable.put(id, job);
		jobRst.put("status", job.getStatus());
		if ("FAIL".equals(job.getStatus())) {
			// throw new ...
		}
		return jobRst;
	}

	@PostMapping("/sync-jobs/{jobType}")
	public Map<String, Object> startSyncJob(@PathVariable("jobType") String jobType) {
		HashMap<String, Object> jobRst = new HashMap<>();
		String id = "TEST-JOB-" + jobIdSeq++;
		jobRst.put("remoteJobId", id);
		MyBizJob job = new MyBizJob();
		jobTable.put(id, job);
		job.runJob();
		jobRst.put("status", job.getStatus());
		if ("FAIL".equals(job.getStatus())) {
			// throw new ...
		}
		return jobRst;
	}

	@GetMapping("/jobstatus/jobs/{id}")
	public String getJobStatus(@PathVariable("id") String id) {
		Object job = jobTable.get(id);
		if (job instanceof TestJobRunner) {
			return ((TestJobRunner) job).getStatus();
		}
		return ((MyBizJob) job).getStatus();
	}

	@DeleteMapping("/jobs/{id}")
	public String stopJob(@PathVariable("id") String id) {
		Object job = jobTable.get(id);
		if (job instanceof TestJobRunner) {
			TestJobRunner job2 = (TestJobRunner) job;
			job2.stopJob();
			return job2.getStatus();
		}
		((MyBizJob) job).stopJob();
		return "STOPPING";
	}
}
